<template>
  <div class="staff-edit-page">
    <el-card>
      <div class="edit-title">编辑职工</div>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="staff-form">
        <div class="form-row">
          <el-form-item label="姓名：" prop="realName">
            <el-input v-model="form.realName" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号：" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="职务：" prop="roleId">
            <el-select v-model="form.roleId" placeholder="请选择职务" filterable>
              <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门：" prop="departmentId">
            <el-select v-model="form.departmentId" placeholder="请选择部门" filterable>
              <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="goBack">取消</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getRoleOptions, getDepartmentOptions, getStaffList, updateStaff } from '@/api/staff'

const router = useRouter()
const route = useRoute()
const formRef = ref()
const form = reactive({
  realName: '',
  phone: '',
  roleId: '',
  departmentId: ''
})

const rules = {
  realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择职务', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择部门', trigger: 'change' }]
}

const roleOptions = ref<{label: string, value: number}[]>([])
const departmentOptions = ref<{label: string, value: number}[]>([])

const getOptions = async () => {
  try {
    const roleRes = await getRoleOptions()
    roleOptions.value = Array.isArray(roleRes) ? roleRes.map(r => ({ label: r.roleName, value: r.id })) : []

    const deptRes = await getDepartmentOptions()
    departmentOptions.value = Array.isArray(deptRes) ? deptRes.map(d => ({ label: d.departmentName, value: d.id })) : []
  } catch (error) {
    ElMessage.error('加载选项失败')
  }
}

onMounted(async () => {
  try {
    // 1. 先加载下拉选项
    await getOptions()

    // 2. 再加载并回显表单数据
    const userId = route.params.userId
    if (userId) {
      const res = await getStaffList({ userId, current: 1, size: 1 }) as any
      let records = []
      if (res && res.records) {
        records = res.records
      }
      if (records && records.length > 0) {
        const staff = records[0]
        // 处理角色和部门数据
        const roleId = staff.roleId || ''
        const departmentId = staff.departmentId || ''
        // 更新表单数据
        Object.assign(form, {
          realName: staff.realName || '',
          phone: staff.phone || '',
          roleId: roleId,
          departmentId: departmentId
        })
      } else {
        ElMessage.warning('未找到职工数据')
      }
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
})

function handleSubmit() {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const userId = route.params.userId
        await updateStaff({
          userId: Number(userId),
          realName: form.realName,
          phone: form.phone,
          roleId: form.roleId,
          departmentId: form.departmentId
        })
        ElMessage.success('编辑成功')
        goBack()
      } catch (error) {
        ElMessage.error('编辑失败')
      }
    }
  })
}

function goBack() {
  router.back()
}
</script>

<style scoped>
.staff-edit-page {
  padding: 40px 24px;
}
.edit-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 24px;
}
.staff-form {
  background: #fafbfc;
  padding: 24px 16px 8px 16px;
  border-radius: 8px;
}
.form-row {
  display: flex;
  gap: 24px;
}
.form-actions {
  margin-top: 24px;
  text-align: left;
}
</style>
